package top.kikt.book.core.handlers

import org.jsoup.nodes.Document
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler
import top.kikt.book.core.handlers.common.CommonBookHandler
import top.kikt.book.util.getUrl
import java.nio.charset.Charset

class Luoqiuzw : BaseBookHandler(), CommonBookHandler {
    override val host: String
        get() = "www.luoqiuzw.com"

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        return CommonBookHandler.parseBookMeta(document, url)
    }

    override fun forceCharset(): Charset = Charset.forName("utf8")
    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val list = document.select("#list > dl")
        val children = list[0].children()

        var dtIndex = 0
        for ((index, child) in children.withIndex()) {
            if (child.tagName() == "dt") {
                dtIndex++
                if (dtIndex == 2) {
                    dtIndex = index
                    break
                }
            }
        }

        return children.subList(dtIndex, children.size).filter {
            it.tagName() == "dd"
        }.mapIndexed { index, it ->
            val a = it.select("a")[0]
            val url = a.getUrl(menuUrl)
            val name = a.text()
            ChapterMetaEntity(name, index, url, a)
        }
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity {
        return CommonBookHandler.parseChapter(chapterMetaEntity, this)
    }
}